<template>
  <div class="mpressRelease">
  <section>
    <!--工具条-->
    <search-bar more-display>
      <el-row>
        <el-col :span="8">
          <el-form-item label="新闻标题">
            <el-input  v-model="searchBarName" placeholder="请输入新闻公告标题"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="接收对像">
            <el-select v-model="receptionValue" placeholder="请选择">
              <el-option
                v-for="(item, index) in $store.getters.NEWS_ANNOUNCEMENT_RECEIVER"
                :label="item.cnDictValname"
                :value="item.dictVal"
                v-bind:key="index">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="创建日期">
            <el-date-picker
              v-model="pressReleaseCreateDate"
              type="daterange"
              align="right"
              placeholder="选择日期范围"
              :picker-options="pickerOptions2"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>

      </el-row>

    </search-bar>

    <!-- 操作 -->
    <el-col :span="24" style="margin-bottom: 10px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="batchDel">批量删除</el-button>

      <el-button type="primary" @click="reset" style="float: right">重置</el-button>
      <el-button type="primary" @click="searchPressRelease" style="float: right">查询</el-button>
    </el-col>

    <!--列表-->
    <el-table :data="tableData" highlight-current-row border @sort-change="sortChange" max-height="650"
              @selection-change="selsChange" v-loading="listLoading" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="title" label="新闻公告标题" >
        <template slot-scope="scope">
          <a style="cursor: pointer;text-decoration:underline;color: #20a0ff" @click="pressReleaseDialog(scope.row)">{{scope.row.title}}</a>
        </template>
      </el-table-column>
      <el-table-column prop="typeModel" label="接收对像" width="280" >
      </el-table-column>
      <el-table-column prop="createDate" label="创建日期" width="280" >
      </el-table-column>
      <el-table-column prop="effectiveDate" label="有效日期至" width="280"  >
      </el-table-column>
      <el-table-column label="操作" width="330">
        <template slot-scope="scope">
          <el-button  type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button  type="primary" @click="modifyStickById(scope.$index, scope.row)">置顶
          </el-button>
          <el-button type="danger"  @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>

    <!-- 弹窗 -->
    <el-dialog :title="dialogTitle" size="middle" :visible.sync="pressReleaseVisible" :close-on-click-modal="false" >
      <el-form :model="pressRelease" :rules="rules" label-width="80px" ref="pressRelease">
        <el-form-item label="公告标题" prop="title" >
          <el-input v-model="pressRelease.title" auto-complete="off" placeholder="请输入公告标题                                                                       2/30" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="接收对像"  required >
          <el-checkbox-group v-model="checkList" >
            <el-checkbox label="114005001">货主</el-checkbox>
            <el-checkbox label="114005002">司机</el-checkbox>
            <el-checkbox label="114005003">事业合伙人</el-checkbox>
            <el-checkbox label="114005004">平台系统用户</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="公告类型"  prop="newsType">
          <el-select placeholder="请选择公告类型" v-model="pressRelease.newsType" style="width: 450px;">
            <el-option v-for="item in $store.getters.NEWS_TYPE"
                       :label="item.cnDictValname"
                       :key="item.dictVal"
                       :value="item.dictVal" style="width: 450px;">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公告图片">
          <el-upload :on-success="handleImgPreview"
                     :before-upload="beforeUploadImg"
                     :show-file-list="false"
                     :headers="this.$store.state.headersAuthorization"
                     action="/api/v3.0/admin/api/file_upload">
            <img v-if="imgsrc == null || imgsrc == ''" src="../../assets/uploadImg.png">
            <img v-else  v-bind:src="imgsrc" style="width: 150px;height: 150px">
          </el-upload>
          <label>只能上传1张jpg/png文件，且文件不超过2M</label><br>
        </el-form-item>
        <el-form-item label="公告来源" prop="resource"  >
          <el-input v-model="pressRelease.resource" auto-complete="off" placeholder="请输入公告来源" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="有效期至" prop="effectiveDate" >

          <el-date-picker
            v-model="pressRelease.effectiveDate"
            type="date"
            placeholder="选择日期"
            style="width: 450px;"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="公告摘要"  prop="mAbstract">
          <el-input type="textarea" v-model="pressRelease.mAbstract" :rows="2" resize="none"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" prop="content" >
          <quill-editor v-model="pressRelease.content"
                        style="width: 100%;height: 150px"
                        ref="myQuillEditor"
                        class="editer">
          </quill-editor>
        </el-form-item>
        <el-form-item prop="fileSrc" style="margin-top: 70px">
          <div style="width: 300px;margin-top: 20px;">
          <el-upload
            action="/api/v3.0/admin/api/batch_upload_files"
            :on-success="handlePreview"
            :on-remove="handleRemove"
            :headers="this.$store.state.headersAuthorization"
            :file-list="fileList">
            <el-button  type="primary" >点击上传附件</el-button>
          </el-upload>
          </div>
        </el-form-item>
        <el-form-item prop="isStick"  >
          <el-checkbox v-model="pressRelease.isStick" :true-label="111002001" :false-label="111002002">置顶该公告
          </el-checkbox>
        </el-form-item>
        <el-form-item v-if="checkList.indexOf('114005001') > -1">----------------------------------------------------------------
          推送设置---------------------------------------------------------------</el-form-item>
        <el-form-item label="是否同步推送消息" v-if="checkList.indexOf('114005001') > -1" >
          <el-radio-group :disabled="dialogTitle !== '新增'" v-model="flag">
            <el-radio label="yes">是</el-radio>
            <el-radio label="no">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="目标用户" v-if="checkList.indexOf('114005001') > -1" >
          <el-radio-group v-model="pressRelease.target" :disabled="dialogTitle !== '新增'">
            <el-radio label="ALL">全部用户</el-radio>
            <el-radio label="PERSON_GROUP">用户分群推送</el-radio>
            <el-radio label="PERSONAL_GRADE">会员等级推送</el-radio>
          </el-radio-group>
          <br v-if="pressRelease.target === 'PERSON_GROUP'">
          <el-select v-model="pressRelease.personalGroupId"
                     v-if="pressRelease.target === 'PERSON_GROUP'"  :disabled="dialogTitle !== '新增'"
                     style="width: 450px">
            <el-option v-for="item in targetList"
                       :label="item.groupName"
                       :key="item.id"
                       :value="item.id"></el-option>
          </el-select>
          <br v-if="pressRelease.target === 'PERSONAL_GRADE'">
          <el-select  v-model="pressRelease.grade"
                      v-if="pressRelease.target === 'PERSONAL_GRADE'"   :disabled="dialogTitle !== '新增'"
                      style="width: 450px">
            <el-option  v-for="item in $store.getters.MEMBERSHIP_GRADE"
                        :label="item.cnDictValname"
                        :key="item.dictVal"
                        :value="item.dictVal"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推送方式" v-if="checkList.indexOf('114005001') > -1">
          <el-radio-group v-model="pressRelease.pushType" :disabled="dialogTitle !== '新增'">
            <el-radio label="REAL_TIME">实时推送</el-radio>
            <el-radio label="TIMING">定时推送</el-radio>
            <br v-if="pressRelease.pushType == 'TIMING'">
            <el-date-picker v-if="pressRelease.pushType == 'TIMING'" style="width: 450px"
                            v-model="pressRelease.timingTime"
                            type="datetime" :disabled="dialogTitle !== '新增'"
                            placeholder="选择日期时间"
                            align="right">
            </el-date-picker>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="handleSubmit" :loading="submitLoading">保存</el-button>
        <el-button @click.native="cancleSubmit">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="新闻公告查看" :visible.sync="pressReleaseVisiable" size="large">
      <press-release :title="pressReleaseForm"></press-release>
    </el-dialog>
  </section>
  </div>
</template>

<script>
import {
  searchPressRelease,
  batchpressReleaseDel,
  savePressRelease,
  modifyStick,
  searchPressReleaseFileByPressReleaseId
} from '../../api/v3/PressRelease';
import {getAllPersonalGroups} from '../../api/v3/PersonalGroup';
import PressRelease from './PressReleaseDialog.vue';
import {createMessage} from '../../api/v3/Message';
export default {
  components: {
    'press-release': PressRelease
  },
  data () {
    return {
      pressReleaseForm: {},
      pressReleaseVisiable: false,
      editorOption: {},
      fileList: [],
      targetList: [],
      form: {
        name: '',
        title: '',
        content: '',
        target: 'ALL',
        personalGroupId: null,
        grade: '',
        pushType: 'REAL_TIME',
        timingTime: '',
        valid: 24
      },
      flag: 'no',
      // 日期控件
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      imgsrc: '',
      checkList: [],
      // 接收对像  start
      receptionValue: '',
      searchBarName: '',
      pressReleaseCreateDate: '',
      // 接收对像  end
      dialogTitle: '',
      condition: {
        name: '',
        number: ''
      },
      sels: [],
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: null,
      sortOrder: 'ascending',
      listLoading: false,
      pressReleaseVisible: false,
      submitLoading: false,
      // 表单数据
      pressRelease: {
        'id': null,
        'title': null,
        'type': null,
        'resource': null,
        'effectiveDate': null,
        'content': null,
        'isStick': null,
        'fileSrc': null,
        'newsType': null,
        'mAbstract': null,
        'target': 'ALL',
        'personalGroupId': null,
        'grade': null,
        'pushType': 'REAL_TIME',
        'timingTime': null
      },
      fileListDetial: [],
      // 验证规则
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 2, max: 30, message: '长度在2到30个文字内', trigger: 'blur'}
        ],
        newsType: [
          {type: 'number', required: true, message: '请选择接收对象', trigger: 'blur'}
        ],
        resource: [
          {min: 2, max: 30, message: '长度在2到30个文字内', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入新闻内容', trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    // 查看新闻
    pressReleaseDialog (val) {
      this.pressReleaseVisiable = true;
      this.pressReleaseForm = val;
    },
    // 新增时，先清空
    myResert () {
      this.checkList.checked = false;
      this.checkList = [];
      if (this.$refs.pressRelease) {
        this.$refs.pressRelease.resetFields();
      }
      for (let p in this.pressRelease) {
        if (this.pressRelease[p] instanceof Array) {
          this.pressRelease[p] = [];
        } else {
          this.pressRelease[p] = null;
        }
      }
      this.pressRelease.target = 'ALL';
      this.pressRelease.pushType = 'REAL_TIME';
    },
    // 搜索
    searchPressRelease () {
      let params = '';
      // 姓名
      if (this.searchBarName !== null && this.searchBarName !== '') {
        params += 'LIKE_title=' + this.searchBarName + ';';
      }
      // 接收对像
      if (this.receptionValue !== null && this.receptionValue !== '') {
        params += 'LIKE_type=' + this.receptionValue + ';';
      }
      // 创建日期
      if (this.pressReleaseCreateDate.length > 0 && this.pressReleaseCreateDate[0] != null && this.pressReleaseCreateDate[1] != null) {
        params += 'GTE_createDate=' + this.pressReleaseCreateDate[0].toJSON() + ';';
        params += 'LTE_createDate=' + this.$ue.addDays(this.pressReleaseCreateDate[1], 1).toJSON() + ';';
      }

      searchPressRelease({
        filters: params,
        page: this.currentPage - 1,
        size: this.pageSize,
        sort: ['isStick,asc', 'stickTime,desc', 'createDate,desc']
      }).then(res => {
        this.tableData = res.data;
        this.total = Number(res.headers['x-total-count']);
        this.listLoading = false;
      });
    },

    // 弹出修改窗口
    handleEdit (index, row) {
      this.resetForm();
      this.myResert();
      this.imgsrc = '';
      this.dialogTitle = '修改';
      this.pressReleaseVisible = true;
      this.pressRelease = Object.assign({}, row);
      this.pressRelease.content = row.content;
      this.checkList = this.pressRelease.type.split(',');
      if (row.imgSrc !== null && row.imgSrc !== '') {
        this.imgsrc = '/' + row.imgSrc;
      }
      searchPressReleaseFileByPressReleaseId(row.id).then((res) => {
        if (res.data) {
          this.fileList = res.data;
        }
      });
    },

    // 重置查询条件
    reset () {
      this.searchBarName = '';
      this.receptionValue = '';
      this.searchBarPhone = '';
      this.pressReleaseCreateDate = '';
      this.isStick = '';
    },

    // 新增修改数据提交
    handleSubmit () {
      // 表单验证
      if (this.pressRelease.isStick === '' || this.pressRelease.isStick == null || this.pressRelease.isStick === undefined) {
        this.pressRelease.isStick = 111002002;
      }
      if (this.pressRelease.newsType === '' || this.pressRelease.newsType == null || this.pressRelease.newsType === undefined) {
        this.$message.error('公告类型不能为空');
        return;
      }
      if (this.checkList.length < 1) {
        this.$message.error('请至少选择一项接收对象');
        return;
      }
      if (this.checkList.indexOf('114005001') > -1 && this.dialogTitle === '新增' && this.pressRelease.effectiveDate !== '' && this.pressRelease.effectiveDate !== null && this.pressRelease.effectiveDate !== undefined && this.form.timingTime !== null && this.form.timingTime !== '' && this.form.timingTime !== undefined && this.form.pushType === 'TIMING') {
        if (this.pressRelease.effectiveDate < this.form.timingTime) {
          this.$message.error('推送时间不能晚于新闻的有效时间');
          return;
        }
      }
      this.$refs['pressRelease'].validate((valid) => {
        this.pressRelease.type = this.checkList.join(',');
        if (this.fileList.length > 0 && this.fileList !== null) {
          this.pressRelease.fileSrc = this.fileList.join(',');
        } else {
          this.pressRelease.fileSrc = null;
        }
        this.pressRelease.imgSrc = this.imgsrc.substring(1, this.imgsrc.length);
        if (valid) {
          this.submitLoading = true;
          savePressRelease(this.pressRelease).then((res) => {
            this.submitLoading = false;
            if (res.data) {
              this.pressReleaseVisible = false;
              this.searchPressRelease();
              this.$message({
                message: '保存成功',
                type: 'success'
              });
            }
          });
        }
      });
      this.imgsrc = '';
      if (this.checkList.indexOf('114005001') > -1 && this.dialogTitle === '新增' && this.flag === 'yes') {
        if (this.pressRelease.mAbstract === '' || this.pressRelease.mAbstract === null || this.pressRelease.mAbstract === undefined) {
          this.$message.error('消息推送时，新闻摘要不能为空！');
          return;
        }
        this.form.name = this.pressRelease.title;
        this.form.title = this.pressRelease.title;
        if (this.pressRelease.mAbstract !== null && this.pressRelease.mAbstract !== undefined) {
          this.form.content = this.pressRelease.mAbstract.length >= 20 ? this.pressRelease.mAbstract.substring(0, 17) + '...' : this.pressRelease.mAbstract;
        } else {
          this.form.content = '';
        }
        this.form.target = this.pressRelease.target;
        this.form.personalGroupId = this.pressRelease.personalGroupId;
        this.form.grade = this.pressRelease.grade;
        this.form.pushType = this.pressRelease.pushType;
        this.form.timingTime = this.pressRelease.timingTime;
        this.submitLoading = true;
        createMessage(this.form).then(res => {
          if (res.data !== null) {
            this.submitLoading = false;
            this.$message.success('推送成功');
            this.resetMessageForm();
          }
        });
      }
    },
    handleRemove (file, fileList) {
      this.fileList.pop(file);
    },
    handlePreview (file) {
      this.fileList.push(file[0]);
    },
    handleImgPreview (file) {
      this.imgsrc = '/' + file[0];
    },
    beforeUploadImg (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 和 png格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 重置表单
    resetForm () {
      if (this.$refs.pressRelease) {
        this.$refs.pressRelease.resetFields();
      }
      for (let p in this.pressRelease) {
        this.pressRelease[p] = null;
      }
      this.pressRelease.target = 'ALL';
      this.pressRelease.pushType = 'REAL_TIME';
    },
    resetMessageForm () {
      for (let p in this.form) {
        this.form[p] = null;
      }
      this.form.pushType = 'REAL_TIME';
      this.form.target = 'ALL';
      this.form.valid = 24;
    },
    // 弹出添加窗体
    handleAdd () {
      this.dialogTitle = '新增';
      this.fileList = [];
      this.resetForm();
      this.myResert();
      this.pressReleaseVisible = true;
    },
    // 多选操作
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchPressRelease();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchPressRelease();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchPressRelease();
    },
    // 重置查询条件
    resetCondition () {
      for (let p in this.condition) {
        this.condition[p] = null;
      }
    },

    // 批量删除
    batchDel () {
      let id = this.sels.map(item => item.id);
      if (id === '' || id == null) {
        this.$message.error('请选择数据！');
        return;
      }
      this.$confirm('确认删除该新闻吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        batchpressReleaseDel(id).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '恭喜删除成功！',
            type: 'success'
          });
          this.searchPressRelease();
        }).catch(function (error) {
          console.log(error);
        });
      });
    },

    // 单条置顶
    modifyStickById (index, row) {
      this.$confirm('确认置顶该新闻公告吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        modifyStick(row.id).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '恭喜置顶成功！',
            type: 'success'
          });
          this.searchPressRelease();
        });
      }).catch(function (error) {
        console.log(error);
      });
    },

    // 删除单条数据操作
    handleDel (index, row) {
      this.$confirm('确认删除该新闻公告吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        batchpressReleaseDel([row.id]).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '恭喜删除成功！',
            type: 'success'
          });
          this.searchPressRelease();
        });
      }).catch(function (error) {
        console.log(error);
      });
    },
    getAllPersonalGroups () {
      getAllPersonalGroups().then(res => {
        this.targetList = res.data;
      });
    },
    // 取消保存
    cancleSubmit () {
      this.$confirm('确认取消保存该新闻公告吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.pressReleaseVisible = false;
        this.searchPressRelease();
        this.reset();
        this.myResert();
        this.imgsrc = '';
      });
    },
    onEditorReady (editor) {
    }
  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill;
    }
  },
  // 初始化数据
  mounted () {
    this.searchPressRelease();
    this.$store.commit('initDict');
    this.getAllPersonalGroups();
  }
};
</script>

<style lang="less">

</style>
